import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import routes from './routes';
import { setupGuard } from './guard';

const router = createRouter({
  history:
    import.meta.env.VITE_ROUTER_HISTORY === 'hash'
      ? createWebHashHistory(import.meta.env.VITE_BASE_URL)
      : createWebHistory(import.meta.env.VITE_BASE_URL),
  routes: routes,
});

setupGuard(router);

export default router;

export const getActive = (maxLevel = 3): string => {
  const route = router.currentRoute.value;

  if (!route || !route.path) {
    return '';
  }

  return route.path
    .split('/')
    .filter((_item: string, index: number) => index <= maxLevel && index > 0)
    .map((item: string) => `/${item}`)
    .join('');
};

export const useActive = (maxLevel = 3) => {
  const active = ref('');

  watch(
    () => router.currentRoute.value,
    (route) => {
      const actionMenu = route.path
        .split('/')
        .filter((_item: string, index: number) => index <= maxLevel && index > 0)
        .map((item: string) => `/${item}`)
        .join('');
      console.log('actionMenu  ', actionMenu);

      active.value = actionMenu;
    },
  );

  return active;
};
